package org.wyy.sample;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 使用zk watch接口,实现同步原语
 * 实现了watch接口的类会注册成为zk的实现回调类,在process()中处理各种事件的回调
 *
 * @author mars
 * @date 2024/1/21
 **/
public class SyncPrimitive implements Watcher {

    static ZooKeeper zk = null;
    /**
     * 声明锁标志
     */
    final static Integer mutex = -1;
    String root;

    SyncPrimitive(String address) {
        if(zk == null){
            try {
                System.out.println("Starting ZK:");
                zk = new ZooKeeper(address, 3000, this);
                //mutex = new Integer(-1);
                System.out.println("Finished starting ZK: " + zk);
            } catch (IOException e) {
                System.out.println(e.toString());
                zk = null;
            }
        }
        //else mutex = new Integer(-1);
    }

    synchronized public void process(WatchedEvent event) {
        synchronized (mutex) {
            System.out.println("Process: " + event.getType());
            mutex.notifyAll();
        }
    }
}
